package com._54programer.observer;

import com._54programer.observer.observer.Observer;

import java.util.ArrayList;
import java.util.List;

public class WeatherData implements Subject {

    private float temperature;
    private float pressure;
    private float humidity;
    //所有注册的观察者
    private List<Observer> observers;

    public WeatherData() {
        this.observers = new ArrayList<Observer>();
    }

    /**
     * 更新数据
     * @param temperature
     * @param pressure
     * @param humidity
     */
    public void setData(float temperature, float pressure, float humidity){
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        //通知所有观察者
        dataChange();
    }

    public void dataChange(){
        notifyObservers();
    }

    /**
     * 注册观察者
     * @param o
     */
    public void registerObserver(Observer o) {
        this.observers.add(o);
    }

    /**
     * 移除观察者
     * @param o
     */
    public void removeObserver(Observer o) {
        if (this.observers.contains(o)){
            this.observers.remove(o);
        }
    }

    /**
     * 通知所有注册的观察者
     */
    public void notifyObservers() {
        for (Observer o : observers) {
            o.update(this.temperature, this.pressure, this.humidity);
        }
    }

}
